package io.jee.caisan.weixin.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import io.jee.alaska.data.jpa.hibernate.condition.Operation;
import io.jee.alaska.util.Result;
import io.jee.caisan.member.client.service.RemoteBalanceChangeService;
import io.jee.caisan.member.client.service.RemoteLevelService;
import io.jee.caisan.weixin.config.UrlManager;
import io.jee.caisan.weixin.domain.Activity;
import io.jee.caisan.weixin.domain.Member;
import io.jee.caisan.weixin.domain.SysActivity;
import io.jee.caisan.weixin.repository.ActivityRepository;
import io.jee.caisan.weixin.service.ActivityService;
import io.jee.caisan.weixin.service.MemberService;
import io.jee.caisan.weixin.service.SysActivityService;
import io.jee.caisan.weixin.utils.DateUtils;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.builder.outxml.NewsBuilder;

@Service
@Transactional
public class ActivityServiceImpl implements ActivityService{
	
	@Resource
	private UrlManager urlManager;
	
	@Resource
	private MemberService memberService;
	
	@Resource
	private ActivityRepository activityRepository;
	
	@Resource
	private RemoteBalanceChangeService remoteBalanceChangeService;
	
	@Resource
	private RemoteLevelService remoteLevelService;
	
	@Resource
	private SysActivityService sysActivityService;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	public WxMpXmlOutMessage xiaodao(WxMpXmlMessage wxMessage) {
		String content = "xiaodao.la";
		String openid = wxMessage.getFromUser();
		
		Member member = memberService.findByOpenid(openid);
		List<Activity> activitys = getActive(member.getMid(), content);
		if(activitys.size() > 0) {//已经参与活动，不再赠送彩豆
			String msg = "获取失败，您已经获得了小刀娱乐网赠送的彩豆，不要贪心哟~";
			return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
		} else {
			//新增活动记录
			addActive(member.getMid(), new BigDecimal("1"), content, "小刀娱乐网赠送");
			//发送参与消息
			String msg = "恭喜您获得小刀娱乐网赠送的1颗彩豆";
			return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
		}
	}
	
	@Override
	public WxMpXmlOutMessage at1024(WxMpXmlMessage wxMessage) {
		String content = "20171024";
		String openid = wxMessage.getFromUser();
		
		try {
			Date d1024 = sdf.parse("2017-10-24");
			Date now = Calendar.getInstance().getTime();
			int day = DateUtils.differentDaysByMillisecond(d1024, now);
			if(day < 0) {//时间小于1024
				String msg = "活动未开始";
				return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
			} else if(day > 0) {//时间大于1024
				String msg = "活动已截止";
				return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
			} else {// 时间等于1024
				Member member = memberService.findByOpenid(openid);
				List<Activity> activitys = getActive(member.getMid(), content);
				//已经赠送
				if(activitys.size() > 0) {
					String msg = "您已经参与1024赠送1彩豆活动，此次不再赠送彩豆，关注我们，再等下一次活动吧";
					return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
				} else {
					//新增活动记录
					addActive(member.getMid(), new BigDecimal("1"), content, "1024活动赠送");
					//发送参与消息
					WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
					item.setTitle("恭喜您，参与1024活动成功");
					item.setDescription("获得彩豆：1颗" + "\n\n更多活动，敬请期待！");
					item.setUrl(urlManager.payIndex());
					new NewsBuilder().build();
					return WxMpXmlOutMessage.NEWS().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).addArticle(item).build();
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public List<Activity> getActive(Integer mid, String content) {
		return activityRepository.select().where("mid", mid).and("content", content).end().list();
	}
	
	public void addActive(Integer mid, BigDecimal caidou, String content, String remark) {
		Result<?> result = remoteBalanceChangeService.caidouPlus(mid, null, mid +"-"+content, caidou, remark);
		if(result.isSuccess()) {
			Activity activity = new Activity();
			activity.setMid(mid);
			activity.setContent(content);
			activity.setCaidou(caidou.toString());
			activity.setCreateTime(Calendar.getInstance().getTime());
			activityRepository.save(activity);
		}
	}

	@Override
	public WxMpXmlOutMessage at1111(WxMpXmlMessage wxMessage) {
		String content = "20171111";
		String openid = wxMessage.getFromUser();
		
		try {
			Date d1024 = sdf.parse("2017-11-11");
			Date now = Calendar.getInstance().getTime();
			int day = DateUtils.differentDaysByMillisecond(d1024, now);
			if(day < 0) {//时间小于1024
				String msg = "活动未开始\n请于2017年11月11日点击此菜单领取1.1彩豆";
				return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
			} else if(day > 0) {//时间大于1024
				String msg = "活动已截止";
				return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
			} else {// 时间等于1024
				Member member = memberService.findByOpenid(openid);
				List<Activity> activitys = getActive(member.getMid(), content);
				//已经赠送
				if(activitys.size() > 0) {
					String msg = "您已经参与双十一赠送1.1彩豆活动，此次不再赠送彩豆，关注我们，再等下一次活动吧";
					return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
				} else {
					//新增活动记录
					addActive(member.getMid(), new BigDecimal("1.1"), content, "双11活动赠送");
					//发送参与消息
					WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
					item.setTitle("恭喜您，参与双十一活动成功");
					item.setDescription("获得彩豆：1.1颗" + "\n\n更多活动，敬请期待！");
					item.setUrl(urlManager.payIndex());
					return WxMpXmlOutMessage.NEWS().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).addArticle(item).build();
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public WxMpXmlOutMessage at1212(WxMpXmlMessage wxMessage) {
		String content = "20171212";
		String openid = wxMessage.getFromUser();
		
		try {
			Date d1024 = sdf.parse("2017-12-12");
			Date now = Calendar.getInstance().getTime();
			int day = DateUtils.differentDaysByMillisecond(d1024, now);
			if(day < 0) {//时间小于1024
				String msg = "活动未开始\n请于2017年12月12日点击此菜单领取1.2颗彩豆";
				return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
			} else if(day > 0) {//时间大于1024
				String msg = "活动已截止\n关注我们，再等下一次活动吧";
				return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
			} else {// 时间等于1024
				Member member = memberService.findByOpenid(openid);
				List<Activity> activitys = getActive(member.getMid(), content);
				//已经赠送
				if(activitys.size() > 0) {
					String msg = "您已经获取了点击菜单赠送1.2颗彩豆活动，每人限领一次";
					return WxMpXmlOutMessage.TEXT().content(msg).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
				} else {
					//新增活动记录
					addActive(member.getMid(), new BigDecimal("1.2"), content, "双12活动赠送");
					//发送参与消息
					WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
					item.setTitle("恭喜您，参与双十二活动成功");
					item.setDescription("获得彩豆：1.2颗" + "\n\n微信端正在努力更新，敬请期待！");
					item.setUrl(urlManager.payIndex());
					return WxMpXmlOutMessage.NEWS().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).addArticle(item).build();
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public WxMpXmlOutMessage auto(WxMpXmlMessage wxMessage, Integer type, String code) {
		SysActivity sysActivity = sysActivityService.findOneByTypeAndCode(type, code);
		if(sysActivity != null) {
			//验证登录
			WxMpXmlOutMessage out = memberService.wxMpVerifyBind(wxMessage);
			if(out != null) return out;
			
			String openid = wxMessage.getFromUser();
			Date now = Calendar.getInstance().getTime();
			if(now.before(sysActivity.getStartTime())) {//当前时间小于开始时间，活动未开始
				return messageBuild(wxMessage, sysActivity.getBeforeMessage(), null, null, null);
			} else if(now.after(sysActivity.getEndTime())) {//当前时间大于结束时间，活动已结束
				return messageBuild(wxMessage, sysActivity.getAfterMessage(), null, null, null);
			} else {//活动时间范围内
				Member member = memberService.findByOpenid(openid);
				if(sysActivity.getCycle() == SysActivity.CYCLE_1) {//活动周期 仅一次
					List<Activity> activityRecords = findActivityRecord(member.getMid(), sysActivity.getCode());
					if(activityRecords.size() > 0) {//已经参与，不能再次参与，返回提示消息
						Activity activity = activityRecords.get(0);
						return messageBuild(wxMessage, sysActivity.getFinishMessage(), activity.getCaidou(), activity.getCredit(), activity.getExp());
					} else {// 参与活动，赠送，增加记录，返回成功消息
						Activity activity = addActivityRecord(member, sysActivity);
						return messageBuild(wxMessage, sysActivity.getCompleteMessage(), activity.getCaidou(), activity.getCredit(), activity.getExp());
					}
				} else if(sysActivity.getCycle() == SysActivity.CYCLE_2) {//活动周期 每天一次
					List<Activity> activityRecords = findActivityRecord(member.getMid(), sysActivity.getCode(), Calendar.getInstance().getTime());
					if(activityRecords.size() > 0) {//已经参与，不能再次参与，返回提示消息
						Activity activity = activityRecords.get(0);
						return messageBuild(wxMessage, sysActivity.getFinishMessage(), activity.getCaidou(), activity.getCredit(), activity.getExp());
					} else {// 参与活动，赠送，增加记录，返回成功消息
						Activity activity = addActivityRecord(member, sysActivity);
						return messageBuild(wxMessage, sysActivity.getCompleteMessage(), activity.getCaidou(), activity.getCredit(), activity.getExp());
					}
				} else if(sysActivity.getCycle() == SysActivity.CYCLE_0) {//活动周期 不限制
					Activity activity = addActivityRecord(member, sysActivity);
					return messageBuild(wxMessage, sysActivity.getCompleteMessage(), activity.getCaidou(), activity.getCredit(), activity.getExp());
				}
			}
			
		}
		return null;
	}
	
	/**
	 * 根据数字转换为小数，包括生成随机数
	 * @param value
	 * @return
	 */
	private float valueToFloat(String value) {
		if(value.indexOf("-") != -1) {//随机取值
			String[] values = value.split("-");
			DecimalFormat decimalFormat = new DecimalFormat("0.00");
			float rand = RandomUtils.nextFloat(Float.valueOf(values[0]), Float.valueOf(values[1]));
			return Float.valueOf(decimalFormat.format(rand));
		} else {
			return Float.valueOf(value);
		}
	}
	
	/**
	 * 根据数字转换为整数，包括生成随机数
	 * @param value
	 * @return
	 */
	private int valueToInt(String value) {
		if(value.indexOf("-") != -1) {//随机取值
			String[] values = value.split("-");
			int rand = RandomUtils.nextInt(Integer.valueOf(values[0]), Integer.valueOf(values[1]));
			return rand;
		} else {
			return Integer.valueOf(value);
		}
	}
	
	/**
	 * 增加活动记录和赠送
	 * @param member
	 * @param sysActivity
	 */
	private Activity addActivityRecord(Member member, SysActivity sysActivity) {
		Activity activity = new Activity();
		activity.setMid(member.getMid());
		activity.setContent(sysActivity.getCode());
		
		String ruleCaidou = sysActivity.getRuleCaidou();
		String ruleCredit = sysActivity.getRuleCredit();
		String ruleExp = sysActivity.getRuleExp();
		if(StringUtils.hasText(ruleCaidou)) {
			float caidou = valueToFloat(ruleCaidou);
			Result<?> result = remoteBalanceChangeService.caidouPlus(member.getMid(), null, member.getMid()+"-"+sysActivity.getCode(), new BigDecimal(String.valueOf(caidou)), sysActivity.getContent());
			if(result.isSuccess()) {
				//TODO
			}
			activity.setCaidou(String.valueOf(caidou));
		}
		if(StringUtils.hasText(ruleCredit)) {
			int credit = valueToInt(ruleCredit);
			Result<?> result = remoteBalanceChangeService.creditDirect(member.getMid(), null, member.getMid()+"-"+sysActivity.getCode(), credit, sysActivity.getContent());
			if(result.isSuccess()) {
				//TODO
			}
			activity.setCredit(String.valueOf(credit));
		}
		if(StringUtils.hasText(ruleExp)) {
			int exp = valueToInt(ruleExp);
			remoteLevelService.expDirect(member.getMid(), exp, sysActivity.getContent());
			activity.setExp(String.valueOf(exp));
		}
		activity.setCreateTime(Calendar.getInstance().getTime());
		activityRepository.save(activity);
		return activity;
	}
	
	/**
	 * 获取活动记录（全部）
	 * @param mid
	 * @param content
	 * @return
	 */
	private List<Activity> findActivityRecord(Integer mid, String content) {
		return activityRepository.select().where("mid", mid).and("content", content).end().list();
	}
	
	/**
	 * 获取活动记录（指定日期）
	 * @param mid
	 * @param content
	 * @param date
	 * @return
	 */
	private List<Activity> findActivityRecord(Integer mid, String content, Date date){
		return activityRepository.select().where("mid", mid).and("content", content)
				.and("createTime", Operation.GET, DateUtils.getDayBegin(date))
				.and("createTime", Operation.LET, DateUtils.getDayEnd(date)).end().list();
	}
	
	/**
	 * 构建消息
	 * @param wxMessage
	 * @param message
	 * @param caidou
	 * @param credit
	 * @param exp
	 * @return
	 */
	private WxMpXmlOutMessage messageBuild(WxMpXmlMessage wxMessage, String message, String caidou, String credit, String exp) {
		if(StringUtils.hasText(message)) {
			String[] strs = message.split("@");//通过@分隔符识别消息类型
			if("text".equals(strs[0])) {//文本消息
				String content = strs[1];
				content = content.replaceAll("#caidou#", StringUtils.hasText(caidou) ? caidou : "无");
				content = content.replaceAll("#credit#", StringUtils.hasText(credit) ? credit : "无");
				content = content.replaceAll("#exp#", StringUtils.hasText(exp) ? exp : "无");
				content = content.replace("\\n", "\n");
				return WxMpXmlOutMessage.TEXT().content(content).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
			} else if("news".equals(strs[0])) {//图文消息
				WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
				item.setTitle(strs[1]);
				String content = strs[2];
				content = content.replaceAll("#caidou#", StringUtils.hasText(caidou) ? caidou : "无");
				content = content.replaceAll("#credit#", StringUtils.hasText(credit) ? credit : "无");
				content = content.replaceAll("#exp#", StringUtils.hasText(exp) ? exp : "无");
				content = content.replace("\\n", "\n");
				item.setDescription(content);
				item.setUrl(strs[3]);
				return WxMpXmlOutMessage.NEWS().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).addArticle(item).build();
			}
			
		}
		return null;
	}

}
